//
//  OAuthViewController.swift
//  MyWeibo
//
//  Created by 余丽丽 on 15/10/10.
//  Copyright © 2015年 余丽丽. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate{
    //单例
    private lazy var webView = UIWebView()
    
    
    // 搭建界面
    override func loadView() {
        view = webView
        webView.delegate = self

        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    
    // 关闭
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权界面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl()))
        
    }

    // MARK: - UIWebViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //重定向
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        //判断是否包含回调地址
        if !urlString.hasPrefix(NetworkTools.sharedTools.redireUri){
            return true
        }
        
        if let query = request.URL?.query where query.hasPrefix("code="){
        
        let code = query.substringFromIndex("code=".endIndex)
            print("code = \(code)")
            //用code 换取token
            loadAccessToken(code)
        }else
        {
            close()
        }
        return false
        
    }
    
    private func loadAccessToken(code :String){
    
        //用code 换取token
        
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            print("error = \(error)")
            print("result = \(result)")
                
            
            if error != nil || result == nil{
                self.DoError()
                return
            }
            
            //字典转模型
            // 1.用token 获取的信息创建用户账号模型
            // 2.异步加载用户信息
            // 3.保存用户信息(模型中完成)
            UserAccount(dict: result! as! [String : AnyObject]).loadUserInfo({ (error) -> () in
                if error != nil{
                    self.DoError()
                    return
                }
                
                //发送通知切换视图控制器
                NSNotificationCenter.defaultCenter().postNotificationName(YLLRootViewControllerSwitchNotification, object: false)
                
                //Modal 出来的控制器 千万千万不要忘记要dismiss
                self.close()
                
            })
            
            
        }
    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    // MARK: 网络出错处理
    private func DoError(){
        SVProgressHUD.showInfoWithStatus("网络不给力")
        //延迟处理
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()){
            self.close()
        }
    }
    
    
    //
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
